package com.song.InfoCenter.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import com.song.InfoCenter.bean.CenterInfo;
import com.song.corebean.Host;
import com.song.corebean.MessageType;
import com.song.corebean.PackageMessage;
import com.song.corebean.utils.CoreUtils;

//SimpleChannelInboundHandler<PackageMessage>
public class CenterHandler  extends  ChannelInboundHandlerAdapter{

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		// TODO Auto-generated method stub
		super.userEventTriggered(ctx, evt);
		
		if( evt instanceof IdleStateEvent)
		{
			IdleStateEvent event = (IdleStateEvent) evt;
			if(event.state()  == IdleState.READER_IDLE)
			{
				System.out.println("---READER_IDLE---");
			}else if(event.state() == IdleState.WRITER_IDLE)
			{
				System.out.println("---WRITER_IDLE---");
			}
			
		}
		
	}

	
	
	public void channelRead(ChannelHandlerContext ctx, Object obj)
			throws Exception {
		System.out.println("注册中心接受数据  ----" + obj);
		PackageMessage msg = (PackageMessage)obj;
		if(msg.head.messageType == MessageType.GET_HOSTS)
		{	
				PackageMessage sndmsg = CoreUtils.ctxToPackageMessage(ctx, MessageType.GET_HOSTS, "data",CenterInfo.hosts);
				System.out.println("发送数据 " +sndmsg);
				ctx.writeAndFlush(sndmsg);
		}else if(msg.head.messageType == MessageType.ADD_HOST){
				Host host = (Host) msg.body.bundle.get("data");
				if(!CenterInfo.hosts.contains(host))
					CenterInfo.hosts.add(host);
		}else if(msg.head.messageType == MessageType.HEART_BEAT_REQ)
		{
			PackageMessage heartBeat = buildHeatBeat();
		    System.out.println(" 注册中心发送 心跳响应信号  : ---> "+ heartBeat);
		    ctx.writeAndFlush(heartBeat);
		}
	}


	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println(cause.getCause());
		ctx.close();
	}


	private PackageMessage buildHeatBeat() {
		PackageMessage message = new PackageMessage();
		message.head.messageType= MessageType.HEART_BEAT_RESP;
		return message;
	    }
	
}
